package com.example.comment.handler;

import com.example.comment.utils.R;
import com.example.comment.utils.SystemException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Optional;

/**
 * @author QingZeyu
 * @date 2024/5/7 16:27
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R<String> paramExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                FieldError fieldError = (FieldError) errors.get(0);
                return R.failed(fieldError.getDefaultMessage());
            }
        }
        return R.failed("请求参数错误！");
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({SystemException.class})
    public R<String> paramExceptionHandler(SystemException e) {

        return R.failed(Optional.ofNullable(e.getMessage()).orElse("系统异常"));
    }
}
